/**************************************************************************
 * Copyright (C) 2012 Tyler Robertson
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **************************************************************************/


#include "Arduino.h"
#include "SPI/SerialPeripheralInterface.h"

void spi_initialize()
{	
	unsigned char clr = 0;
	
	pinMode( MISO, INPUT  );
	pinMode( MOSI, OUTPUT );
	pinMode( SCK,  OUTPUT );
	pinMode( SS,   OUTPUT );

	SPCR = (1<<SPE) | (1<<MSTR) /*	| (1<<SPR1) | (1<<SPR0)*/	;
	
	clr = SPDR;
		
	delay( 10 );
	
	Serial.println( "SPI Initialized" );	
}

unsigned char spi_transfer_byte( volatile unsigned char data )
{
	SPDR = data;
	while( !(SPSR & (1<<SPIF)) );
	return SPDR;	
}	   
	   
unsigned char spi_read_byte()
{
	return spi_transfer_byte( 0 );
}

void spi_write_byte( unsigned char data )
{
 	spi_transfer_byte( data );
}

void spi_read_array( unsigned char *array, unsigned long num_bytes )
{
	for( int i=0; i<num_bytes; ++i )
		array[i] = spi_transfer_byte( 0 );
}

void spi_write_array( const unsigned char *array, unsigned long num_bytes )
{
	for( int i=0; i<num_bytes; ++i )
    {
		//Serial.println( array[i], HEX );
		spi_transfer_byte( array[i] );
    }
}

void spi_select_slave( unsigned char slave )
{
	// Slaves are active low
	digitalWrite( slave, LOW );
}

void spi_deselect_slave( unsigned char slave )
{
	// Slaves are active low
	digitalWrite( slave, HIGH );
}
